package network.httpserver;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class ChannelIO {

	protected SocketChannel socketChannl;
	protected ByteBuffer requestBuffer;
	private static int requestBufferSize = 4096;
	
	public ChannelIO(SocketChannel socketChannel, boolean blocking) throws IOException{
		this.socketChannl = socketChannel;
		socketChannel.configureBlocking(blocking);
		requestBuffer = ByteBuffer.allocate(requestBufferSize);
	}
	
	public SocketChannel getSocketChannel(){
		return socketChannl;
	}
	
	protected void resizeRequestBuffer(int remaining){
		if(requestBuffer.remaining() < remaining){
			ByteBuffer bb = ByteBuffer.allocate(requestBuffer.capacity() * 2);
			requestBuffer.flip();
			bb.put(requestBuffer);
			requestBuffer = bb;
		}
	}
	
	public int read() throws IOException{
		resizeRequestBuffer(requestBufferSize/20);
		int n = socketChannl.read(requestBuffer);
//		int position = requestBuffer.position();
//		int limit = requestBuffer.limit();
//		requestBuffer.flip();
//		System.out.println("total bytes:" + n + "\n" + Charset.forName("UTF-8").decode(requestBuffer).toString());
//		requestBuffer.position(position);
//		requestBuffer.limit(limit);
		return n;
	}
	
	public ByteBuffer getReadBuf(){
		return requestBuffer;
	}
	
	public int write(ByteBuffer src) throws IOException{
		return socketChannl.write(src);
	}
	
	/*
	 * 将文件内容写到SocketChannel中
	 */
	public long transerTo(FileChannel fc, long pos, long len) throws IOException{
		return fc.transferTo(pos, len, socketChannl);
	}
	
	public void close() throws IOException{
		socketChannl.close();
	}
	
}
